import Http from '../config/Http'
import {server, api} from '../config/index'
import {StoreState} from '../types'
import reducers from '../reducers';
import {createStore} from 'redux'
import {showAlert} from '../actions'

declare var md5:any;

export const store = createStore<StoreState>(reducers, {
    alertState: false,
    msg: ""
});

export const createSign = (params: any)=>{
    var keys = [];
    for(var key in params) {
        keys.push(key);
    }
    keys.sort();
    var values = [];
    for(var i = 0; i < keys.length; i++) {
        values.push(params[keys[i]]);
    }
    var str = values.join("") + server.appKey;
    return md5(str).toString();
}

export const LoginReq = (username: string, password: string, checkbox: boolean) => {
    let md5Pass:string = md5(password);
    let data:any = {
        appId: server.appId,
        accountType: 0,
        userName: username,
        password: md5Pass,
        code: "",
        redirectUrl: "",
        exInfo: ""
    };
    data["sign"] = createSign(data);
    Http("POST", api.ip+api.login, data).then((res:any) => {
        if(res.code == 200){
            if(checkbox){
                localStorage.setItem("username", JSON.stringify(username));
                localStorage.setItem("password", JSON.stringify(password));
            }
        }else{
            store.dispatch(showAlert("Login fail"));
        }
    })
}




